﻿using System.Text;
using Newtonsoft.Json;
using TaskManagerLib.MinimumWork;
using TaskManagerLib.Symbol;

namespace TaskManagerLib.Test;
// : IMiniWork
public class PostWork: MiniWork
{
    public override bool IsFinished()
    {
        return Status == WorkStatus.Finish;
    }

    public string Url
    {
        get;
        set;
    }

    public string Authorization
    {
        get;
        set;
    }

    public Translate Translate
    {
        get;
        set;
    }

    public PostWork(string url, string authorization, Translate translate)
    {
        Url = url;
        Authorization = authorization;
        Translate = translate;
    }

    public PostWork(CancellationTokenSource source, string url, string authorization, Translate translate)
    {
        CancellationTokenSource = source;
        Url = url;
        Authorization = authorization;
        Translate = translate;
    }

    public override async Task Action()
    {
        using var httpClient = new HttpClient();
        try
        {
            // Set the Authorization header
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(Authorization);

            // Convert Translate object to JSON
            var json = JsonConvert.SerializeObject(Translate);

            // Create the HTTP request content
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            // Send the POST request and get the response
            var response = await httpClient.PostAsync(Url, content);
            response.EnsureSuccessStatusCode();

            var stream = await response.Content.ReadAsStreamAsync();
            var buffer = new byte[102];
            int bytesRead;

            var token1 = CancellationTokenSource?.Token;

            var stringBuilder = new StringBuilder();
            while ((bytesRead = await stream.ReadAsync(buffer,0,4,CancellationTokenSource?.Token ?? CancellationToken.None))>0&&token1 is not
                   {
                       IsCancellationRequested: true
                   })
            {
                stringBuilder.Append(Encoding.UTF8.GetString(buffer,0,bytesRead));
            }

            Result = stringBuilder.ToString();
            Status = WorkStatus.Finish;
            Notification?.Invoke(new ProgressNotification()
            {
                Progress = 100
            });
            Console.WriteLine($"{InnerTask?.GetHashCode()} End At {DateTime.Now}" +
                              $"\n Result is {Result}");
        }
        catch (Exception e)
        {
            Status = WorkStatus.Except;
        }
    }


    public override bool Resume(CancellationTokenSource cancellationTokenSource)
    {
        if (InnerTask?.Status == TaskStatus.Running)
        {
            return false;
        }
        CancellationTokenSource = cancellationTokenSource;
        Build();
        Status = WorkStatus.Ready;
        return true;
    }

}